import React, { useState } from 'react';
import { Button, Input, Card, message, Spin, Modal } from 'antd';
import axios from 'axios';
import img1 from '../../assets/imgs/2.png';

const { TextArea } = Input;

interface Message {
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
}

function Tupi1() {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);

  // 百度智能云API配置
  const API_URL = "https://qianfan.baidubce.com/v2/chat/completions";
  const API_KEY = "bce-v3/ALTAK-K3cQIcUntkJ5niY0Fbm1c/02fbe8f7cc076f8610df688a9ced502c147a59ea";

  // 生成AI内容
  const generateContent = async (prompt: string) => {
    try {
      setLoading(true);
      
      const response = await axios.post(API_URL, {
        model: "ernie-x1.1-preview",
        messages: [
          {
            role: "user",
            content: prompt
          }
        ]
      }, {
        headers: {
          Authorization: `Bearer ${API_KEY}`
        }
      });

      console.log('AI Response:', response.data);
      
      if (response.data.choices && response.data.choices[0]) {
        const aiResponse = response.data.choices[0].message.content;
        
        const newMessage: Message = {
          role: 'assistant',
          content: aiResponse,
          timestamp: Date.now()
        };
        
        setMessages(prev => [...prev, newMessage]);
        message.success('AI回复成功！');
      } else {
        message.error('AI响应格式异常');
      }
    } catch (error) {
      console.error('AI生成失败:', error);
      message.error('AI生成失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage: Message = {
      role: 'user',
      content: inputValue,
      timestamp: Date.now()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    
    await generateContent(inputValue);
  };

  // 快速生成预设内容
  const quickGenerate = async (prompt: string) => {
    await generateContent(prompt);
  };

  // 打开AI对话
  const openAIChat = () => {
    setIsModalVisible(true);
    // 自动发送欢迎消息
    if (messages.length === 0) {
      quickGenerate("你好，我是小明，请帮我写一篇关于人工智能的文章");
    }
  };

  // 关闭AI对话
  const closeAIChat = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <img 
        src={img1} 
        width='50px' 
        style={{ cursor: 'pointer' }}
        onClick={openAIChat}
        title="点击打开AI智能对话"
      />
      
      <Modal
        title="🤖 百度智能云AI对话"
        open={isModalVisible}
        onCancel={closeAIChat}
        footer={null}
        width={800}
        style={{ top: 20 }}
      >
        <div style={{ marginBottom: '20px' }}>
          <div style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}>
            <Button onClick={() => quickGenerate("你好，我是小明，请帮我写一篇关于人工智能的文章")} disabled={loading}>
              生成AI文章
            </Button>
            <Button onClick={() => quickGenerate("请帮我写一首关于春天的诗")} disabled={loading}>
              生成诗歌
            </Button>
            <Button onClick={() => quickGenerate("请帮我写一个简单的JavaScript函数")} disabled={loading}>
              生成代码
            </Button>
            <Button onClick={() => quickGenerate("请帮我解释一下什么是机器学习")} disabled={loading}>
              解释概念
            </Button>
          </div>

          <div style={{ marginBottom: '20px' }}>
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              placeholder="输入你的问题或需求..."
              rows={3}
              style={{ marginBottom: '10px' }}
            />
            <Button 
              type="primary" 
              onClick={sendMessage} 
              disabled={loading || !inputValue.trim()}
              style={{ width: '100%' }}
            >
              {loading ? <Spin size="small" /> : '发送'}
            </Button>
          </div>
        </div>

        <Card title="💬 对话记录" style={{ maxHeight: '400px', overflowY: 'auto' }}>
          {messages.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
              点击上方按钮开始AI对话！
            </div>
          ) : (
            messages.map((msg, index) => (
              <div
                key={index}
                style={{
                  marginBottom: '15px',
                  padding: '10px',
                  borderRadius: '8px',
                  backgroundColor: msg.role === 'user' ? '#e6f7ff' : '#f6ffed',
                  border: `1px solid ${msg.role === 'user' ? '#91d5ff' : '#b7eb8f'}`
                }}
              >
                <div style={{ 
                  fontWeight: 'bold', 
                  marginBottom: '5px',
                  color: msg.role === 'user' ? '#1890ff' : '#52c41a'
                }}>
                  {msg.role === 'user' ? '👤 用户' : '🤖 AI助手'}
                </div>
                <div style={{ whiteSpace: 'pre-wrap' }}>
                  {msg.content}
                </div>
                <div style={{ 
                  fontSize: '12px', 
                  color: '#999', 
                  marginTop: '5px',
                  textAlign: 'right'
                }}>
                  {new Date(msg.timestamp).toLocaleTimeString()}
                </div>
              </div>
            ))
          )}
        </Card>
      </Modal>
    </div>
  );
}

export default Tupi1
